<template>
  <view class="container">
    <!-- 导航栏 -->
    <view class="navbar">
      <view class="navbar-left">
        <view class="back-icon"></view>
      </view>
      <view class="navbar-title">智能问答</view>
      <view class="navbar-right"></view>
    </view>

    <!-- 聊天内容区 -->
    <view class="chat-container">
      <view class="message-list">
        <!-- 消息项 -->
        <view v-for="(msg, index) in messages" :key="index" class="message-item" :class="{ 'user-message': msg.isUser }">
          <image :src="msg.isUser ? '/static/chat_user.png' : '/static/chat_agent.png'" class="avatar"></image>
          <view class="message-bubble">
            <!-- 显示加载状态 -->
            <view v-if="msg.isLoading" class="loading-indicator">
              <image src="/static/loading.gif" class="loading-icon"></image>
            </view>
            {{ msg.content }}
          </view>
        </view>
      </view>

      <!-- 输入区 -->
      <view class="input-area">
        <input 
          v-model="inputContent" 
          class="input" 
          placeholder="请输入您的问题..."
          @confirm="sendMessage"
        />
        <button class="send-btn" @click="sendMessage">发送</button>
      </view>
    </view>
  </view>
</template>

<script>
import config from '../../config.js';

export default {
  data() {
    return {
      messages: [],
      inputContent: '',
      sessionId: '',
      currentBotMessage: null,
      currentRequestTask: null, 
      chunkBuffer: '',
      isFirstChunkReceived: false, // 新增：标记是否已收到第一个数据分片
      hospitalNumber: uni.getStorageSync('hospitalNumber'), // 获取本地存储的住院号
      openid: ''
    };
  },
  onLoad() {
    //this.getOpenid();
	this.checkSession();
  },
  onUnload() {
    // 页面卸载时保存会话ID
    if (this.sessionId) {
      uni.setStorageSync('qaSessionId', this.sessionId);
    }
    
    // 取消正在进行的请求
    this.cancelRequest();
  },
  methods: {
    // 获取OpenID
    async getOpenid() {
      try {
        const { code } = await uni.login({});
        const res = await uni.request({
          url: `${config.baseUrl}/messageAlert/getOpenid`,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': uni.getStorageSync('token') || ''
          },
          data: {
            code,
            hospitalNumber: this.hospitalNumber
          }
        });
        if (res.statusCode === 200 && res.data.code === 200) {
          this.openid = res.data.openid;
          this.requestMessageSubscription();
        } else {
          uni.showToast({
            title: '获取OpenID失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取OpenID失败', error);
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    },
    // 请求消息订阅授权
    async requestMessageSubscription() {
      try {
        const res = await uni.requestSubscribeMessage({
          tmplIds: ['ozKtwr8g1q2maOP4P4r7jaiJit-YiX66rbjajNjDh3w']
        });
        if (res['ozKtwr8g1q2maOP4P4r7jaiJit-YiX66rbjajNjDh3w'] === 'accept') {
          await uni.request({
            url: `${config.baseUrl}/messageAlert/addAuthority`,
            method: 'POST',
            header: {
              'Content-Type': 'application/json',
              'Authorization': uni.getStorageSync('token') || ''
            },
            data: {
              openid: this.openid,
              hospitalNumber: this.hospitalNumber
            }
          });
        }
        this.checkSession();
      } catch (error) {
        console.error('请求消息订阅授权失败', error);
        this.checkSession();
      }
    },
    // 检查会话
    async checkSession() {
      const storedSessionId = uni.getStorageSync('qaSessionId');
      if (storedSessionId) {
        this.sessionId = storedSessionId;
      } else {
        this.createSession();
      }
      this.getHistoryQa();
    },
    // 创建会话
    async createSession() {
      try {
        const res = await uni.request({
          url: `${config.baseUrl}/smartqa/createSession`,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': uni.getStorageSync('token') || ''
          }
        });
        if (res.statusCode === 200 && res.data.code === 200) {
          this.sessionId = res.data.sessionId;
          uni.setStorageSync('qaSessionId', this.sessionId);
        } else {
          uni.showToast({
            title: '会话创建失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('创建会话失败', error);
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    },
    // 获取历史问答
    async getHistoryQa() {
      try {
        const res = await uni.request({
          url: `${config.baseUrl}/messageAlert/historyQa`,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': uni.getStorageSync('token') || ''
          },
          data: {
            hospitalNumber: this.hospitalNumber
          }
        });
		console.log('历史问答返回数据:', res.data);
		console.log(res)
		console.log(res.data.data.historyQa)
        if (res.statusCode === 200 && res.data.code === 200) {
          const historyQa = res.data.data.historyQa;
          if (historyQa.length === 0) {
            this.messages.push({
              content: "你好！有什么我可以帮助你的吗？",
              isUser: false,
              isLoading: false
            });
          } else {
			const reversedHistoryQa = [...historyQa].reverse();
            reversedHistoryQa.forEach(item => {
              this.messages.push({
                content: item.question,
                isUser: true,
                isLoading: false
              });
              this.messages.push({
                content: item.answer,
                isUser: false,
                isLoading: false
              });
            });
          }
        }
      } catch (error) {
        console.error('获取历史问答失败', error);
      }
    },
    // 发送消息
    sendMessage() {
      const question = this.inputContent.trim();
      if (!question || question.length > 60) {
        uni.showToast({
          title: '问题不能为空且不能超过60字',
          icon: 'none'
        });
        return;
      }

      // 添加用户消息
      this.messages.push({
        content: question,
        isUser: true,
        isLoading: false
      });
      this.inputContent = '';
      
      // 添加机器人消息（初始显示加载状态）
      const botMessage = {
        content: '',
        isUser: false,
        isLoading: true
      };
      this.messages.push(botMessage);
      this.currentBotMessage = botMessage;
      this.chunkBuffer = ''; // 重置分片缓冲区
      
      // 使用微信小程序的流式请求API
      this.streamRequest(question);
    },
    // 流式请求处理
    streamRequest(question) {
      // 取消之前的请求（如果有）
      this.cancelRequest();
      
      // 重置标记
      this.isFirstChunkReceived = false;
      
      // 创建新的请求任务
      this.currentRequestTask = uni.request({
        url: `${config.baseUrl}/smartqa/chat`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': uni.getStorageSync('token') || ''
        },
        data: {
          sessionId: this.sessionId,
          question,
          hospitalNumber: this.hospitalNumber
        },
        responseType: 'text',
        enableChunked: true,
        success: (response) => {
          console.log('完整响应:', response);
        },
        fail: (error) => {
          console.error('请求失败', error);
          this.currentBotMessage.content = '获取回答失败: ' + error.errMsg;
          this.currentBotMessage.isLoading = false;
          this.$forceUpdate();
        },
        complete: () => {
          this.currentBotMessage.isLoading = false;
          this.$forceUpdate();
          this.currentRequestTask = null;
        }
      });
      
      // 监听分块数据接收事件
      this.currentRequestTask.onChunkReceived((res) => {
          console.log('收到数据分片', res);
          try {
            const chunkString = this.arrayBufferToString(res.data);
            console.log('分片内容:', chunkString);
            
            // 新增：如果是第一个分片，关闭加载状态
            if (!this.isFirstChunkReceived) {
              this.isFirstChunkReceived = true;
              this.currentBotMessage.isLoading = false;
            }
            
            this.currentBotMessage.content += chunkString;
            this.$forceUpdate();
          } catch (error) {
            console.error('处理分块数据失败', error);
          }
        });
    },
    // 将 ArrayBuffer 转换为字符串（兼容性处理）
    arrayBufferToString(buffer) {
      try {
        // 尝试使用 TextDecoder
        if (typeof TextDecoder !== 'undefined') {
          const decoder = new TextDecoder('utf-8');
          return decoder.decode(new Uint8Array(buffer));
        }
      } catch (e) {
        console.warn('TextDecoder不可用，使用降级方案');
      }
      
      // 降级方案
      const bytes = new Uint8Array(buffer);
      let str = '';
      for (let i = 0; i < bytes.length; i++) {
        str += String.fromCharCode(bytes[i]);
      }
      return str;
    },
    // 取消当前请求
    cancelRequest() {
      if (this.currentRequestTask) {
        this.currentRequestTask.abort();
        this.currentRequestTask = null;
      }
    }
  }
};
</script>

<style scoped>
/* 样式部分保持不变 */
.container {
  background-color: #f5f7fa;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.navbar {
  display: flex;
  align-items: center;
  height: 44px;
  background-color: #1677ff;
  color: #fff;
  padding: 0 16px;
}

.navbar-left {
  width: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 20px;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 17px;
  font-weight: bold;
}

.navbar-right {
  width: 44px;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
}

.message-item {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-start;
}

.message-item.user-message {
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.user-message .avatar {
  margin-right: 0;
  margin-left: 10px;
}

/* 修改后的消息气泡样式 */
.message-bubble {
  position: relative;
  max-width: 70%;
  padding: 10px 14px;
  border-radius: 18px;
  word-wrap: break-word;
}

.message-item:not(.user-message) .message-bubble {
  background-color: #fff;
  border: 1px solid #ebeef5;
}

.user-message .message-bubble {
  background-color: #1677ff;
  color: #fff;
}

.input-area {
  display: flex;
  margin-top: 16px;
  gap: 10px;
}

.input {
  flex: 1;
  height: 44px;
  border: 1px solid #ebeef5;
  border-radius: 22px;
  padding: 0 16px;
  font-size: 14px;
}

.send-btn {
  width: 80px;
  height: 44px;
  background-color: #1677ff;
  color: #fff;
  border-radius: 22px;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 新增的加载指示器样式 */
.loading-indicator {
  display: inline-block;
  margin-right: 8px;
  vertical-align: middle;
}

.loading-icon {
  width: 20px;
  height: 20px;
}
</style>